<template>
  <div>
    <el-echarts theme="green" class="mb-5" :option="ovTopOption"></el-echarts>

    <el-echarts theme="green" :option="ovFarmOption"></el-echarts>
  </div>
</template>
<script>
import { echartsXFormatter } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    addressCode: String,
    startTime: String,
    endTime: String,
  },
  data() {
    return {
      apiTop: '/industrial/pc/product/top10/',
      apiFarm: '/industrial/pc/product/farm/Analysis/',
      ovTopOption: null,
      ovFarmOption: null,
    }
  },
  computed: {
    orgAddress() {
      return this.addressCode || this.$store.getters.org.addressCode || '520000000000'
    },
    urlTop() {
      return `${this.apiTop}?addressCode=${this.orgAddress}&startTime=${
        this.startTime || ''
      }&endTime=${this.endTime || ''}`
    },
    urlFarm() {
      return `${this.apiFarm}?addressCode=${this.orgAddress}&startTime=${
        this.startTime || ''
      }&endTime=${this.endTime || ''}`
    },
  },
  watch: {
    addressCode() {
      this.getData()
    },
  },
  created() {
    this.getData()
  },
  mounted() {},
  methods: {
    async getData() {
      let [res, err] = await this.$utils.promise(this.$http.get(this.urlTop))
      if (err) return

      const ovTopData = res.data.proportionTable
      const ovTotal = res.data.outputValueSum

      const colors = [
        '#ffcc00',
        '#f4c928',
        '#f4aa28',
        '#ff8e00',
        '#ff7100',
        '#f47a28',
        '#ff5100',
        '#ff3d00',
        '#ff2800',
        '#ff1400',
      ]

      ovTopData.sort((a, b) => b.unitPrice - a.unitPrice)

      const chartData = {
        title: '产品产值TOP10及占比分析',
        subtext: '',
        legend: ['产值（元）'],
        category: [],
        data: [],
      }

      let ovTotalTop = 0
      for (let i = 0; i < ovTopData.length; i++) {
        chartData.category.push(ovTopData[i].productName)
        chartData.data.push(ovTopData[i].unitPrice)
        ovTotalTop += ovTopData[i].unitPrice
      }
      const topRatio = (ovTotalTop / ovTotal) * 100
      chartData.subtext =
        '总产值：' +
        ovTotal +
        ' 元，TOP10总产值：' +
        ovTotalTop +
        ' 元，占比' +
        topRatio.toFixed(2) +
        '%'

      this.ovTopOption = {
        title: {
          text: chartData.title,
          subtext: chartData.subtext,
          subtextStyle: {
            color: '#333',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        legend: {
          data: chartData.legend,
          x: 'right',
          y: '20',
        },
        grid: {
          left: '3%',
          right: '8%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'value',
          position: 'top',
          boundaryGap: [0, 0.01],
        },
        yAxis: {
          type: 'category',
          data: chartData.category,
        },
        series: [
          {
            name: chartData.legend[0],
            type: 'bar',
            data: chartData.data,
            itemStyle: {
              normal: {
                color: value => {
                  return colors[value.dataIndex]
                },
                label: {
                  show: true,
                  position: 'right',
                  formatter: value => {
                    return value.value + ' (' + ((value.value / ovTotal) * 1000).toFixed(2) + '‰)'
                  },
                },
              },
              emphasis: {
                label: {
                  show: true,
                  textStyle: {
                    color: 'red',
                    fontWeight: 'bold',
                  },
                },
              },
            },
          },
        ],
      }

      this.chartOvFarm(ovTopData)
    },

    // 产值与主体关联分析
    async chartOvFarm(ovTopData) {
      let [res, err] = await this.$utils.promise(this.$http.get(this.urlFarm))
      if (err) return

      const farmData = res.data
      for (let j = 0; j < farmData.length; j++) {
        const index = ovTopData.findIndex(it => it.productName === farmData[j].product_name)
        if (index > -1) {
          ovTopData[index].farmCount = farmData[j].farmCount
        }
      }

      const chartData = {
        title: '产值与主体关联分析',
        subtext:
          '从生产主体的数量和平均产值，分析发展产业的有效性。平均产值贡献越高，说明单位主体的生产转化率越高，可考虑为重点发展产业',
        legend: ['农场数', '平均产值'],
        xData: [],
        seriesBar: [],
        seriesLine: [],
      }

      for (let i = 0; i < ovTopData.length; i++) {
        chartData.seriesLine.push((ovTopData[i].unitPrice / ovTopData[i].farmCount).toFixed(0))
        chartData.seriesBar.push(ovTopData[i].farmCount)
        chartData.xData.push(ovTopData[i].productName)
      }

      this.ovFarmOption = {
        title: {
          text: chartData.title,
          subtext: chartData.subtext,
          subtextStyle: {
            color: '#333',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        toolbox: {
          show: true,
          x: 'right',
          feature: {
            saveAsImage: {
              show: true,
            },
            dataView: {
              show: true,
              readOnly: true,
            },
            magicType: {
              type: ['line', 'bar'],
            },
            restore: {
              show: true,
            },
          },
        },
        legend: {
          data: chartData.legend,
          x: 'center',
        },
        grid: {
          y: 80,
        },
        xAxis: [
          {
            type: 'category',
            data: chartData.xData,
            axisLabel: {
              interval: 0,
              formatter: v => echartsXFormatter(v, 3),
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '主体数（个）',
            axisLabel: {
              formatter: '{value} 个',
            },
          },
          {
            type: 'value',
            name: '平均产值（元）',
            axisLabel: {
              formatter: '￥{value}',
            },
          },
        ],
        series: [
          {
            name: chartData.legend[0],
            type: 'bar',
            data: chartData.seriesBar,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#615a5a',
                  },
                },
              },
            },
          },
          {
            name: chartData.legend[1],
            type: 'line',
            yAxisIndex: 1,
            data: chartData.seriesLine,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#0036ef',
                  },
                },
              },
            },
          },
        ],
      }
    },
  },
}
</script>
<style scoped></style>
